"use client"

import { useEffect, useRef, useState } from "react"
import { Camera, Play, Slash, ZoomIn, ZoomOut, Maximize2 } from "lucide-react"

interface CameraFeedProps {
  type: "student" | "content"
  isActive: boolean
  className?: string
  isPrimary?: boolean
  pipMode?: boolean
  onSwitchCamera?: () => void
  videoSrc?: string | null // 新增视频源prop
  networkError?: boolean // 新增网络错误prop
}

export function CameraFeed({
  type,
  isActive,
  className,
  isPrimary = true,
  pipMode = false,
  onSwitchCamera,
  videoSrc: propVideoSrc, // 重命名避免命名冲突
  networkError: propNetworkError,
}: CameraFeedProps) {
  const videoRef = useRef<HTMLVideoElement | HTMLImageElement>(null)
  const [zoomLevel, setZoomLevel] = useState(1)
  const [internalError, setInternalError] = useState<string | null>(null)

  // 优先使用外部传入的错误状态
  const hasError = propNetworkError ?? !!internalError

  const handleZoom = (direction: "in" | "out" | "reset") => {
    if (direction === "in") {
      setZoomLevel((prev) => Math.min(prev + 0.25, 3))
    } else if (direction === "out") {
      setZoomLevel((prev) => Math.max(prev - 0.25, 0.5))
    } else {
      setZoomLevel(1)
    }
  }

  const handleClick = (e: React.MouseEvent) => {
    e.stopPropagation()
    console.log("画中画点击事件触发pipMode:") // 调试日志
    
    if (onSwitchCamera && !pipMode) {
      onSwitchCamera()
    }
  }

  useEffect(() => {
    if (!isActive) return

    if (propVideoSrc) {
      const img = new Image()
      img.src = propVideoSrc
      img.onload = () => {
        if (videoRef.current instanceof HTMLImageElement) {
          videoRef.current.src = propVideoSrc
        }
      }
      img.onerror = () => setInternalError("视频帧加载失败")
    }

    return () => {
      if (propVideoSrc) {
        URL.revokeObjectURL(propVideoSrc)
      }
    }
  }, [propVideoSrc, isActive])

  return (
    <div
      className={`relative ${className} overflow-hidden ${
        !pipMode && isPrimary ? "cursor-pointer" : ""
      }`}
      onClick={handleClick}
    >
      {isActive && !hasError ? (
        <>
          {propVideoSrc ? (
            <img
              ref={videoRef as React.RefObject<HTMLImageElement>}
              src={propVideoSrc}
              alt="video"
              className="w-full h-full object-cover transition-transform duration-200"
              style={{ transform: isPrimary ? `scale(${zoomLevel})` : "none" }}
            />
          ) : (
            <div className="absolute inset-0 flex items-center justify-center bg-black/80">
              <Play className={`w-12 h-12 text-muted-foreground ${pipMode ? "w-6 h-6" : ""}`} />
            </div>
          )}

          {!pipMode && (
            <div className="absolute top-2 right-2 bg-green-500/80 text-white text-xs px-2 py-1 rounded-full flex items-center">
              <div className="w-2 h-2 bg-white rounded-full mr-1 animate-pulse"></div>
              实时监控中
            </div>
          )}

          {isPrimary && !pipMode && isActive && (
            <div className="absolute bottom-2 left-2 flex items-center gap-2 bg-black/70 rounded-md p-2 text-white">
              <button
                onClick={(e) => {
                  e.stopPropagation()
                  handleZoom("out")
                }}
                className="p-1.5 rounded-md hover:bg-white/20 transition-colors"
                title="缩小"
              >
                <ZoomOut className="w-5 h-5" />
              </button>
              <div className="min-w-[48px] text-center font-medium">
                {Math.round(zoomLevel * 100)}%
              </div>
              <button
                onClick={(e) => {
                  e.stopPropagation()
                  handleZoom("in")
                }}
                className="p-1.5 rounded-md hover:bg-white/20 transition-colors"
                title="放大"
              >
                <ZoomIn className="w-5 h-5" />
              </button>
              <button
                onClick={(e) => {
                  e.stopPropagation()
                  handleZoom("reset")
                }}
                className="p-1.5 rounded-md hover:bg-white/20 transition-colors ml-1"
                title="重置缩放"
              >
                <Maximize2 className="w-5 h-5" />
              </button>
            </div>
          )}
        </>
      ) : (
        <div className="absolute inset-0 flex items-center justify-center bg-muted">
          {hasError ? (
            <div className="text-center text-destructive">
              <Slash className={`mx-auto mb-2 ${pipMode ? "w-6 h-6" : "w-12 h-12"}`} />
              {!pipMode && <p>视频流异常，请检查网络连接</p>}
            </div>
          ) : (
            <div className="text-center">
              <Play className={`mx-auto mb-2 text-muted-foreground ${pipMode ? "w-6 h-6" : "w-12 h-12"}`} />
              {!pipMode && <p className="text-muted-foreground">点击"开始监控"按钮启动摄像头</p>}
            </div>
          )}
        </div>
      )}

      {pipMode && (
        <div className="absolute inset-0 bg-black/40 opacity-0 hover:opacity-100 transition-opacity flex items-center justify-center">
          <div className="text-white text-xs font-medium">点击切换</div>
        </div>
      )}
    </div>
  )
}